/*
 *@Description: 自动采集书籍信息
 *@Author: panlua
 *@Date: 2019-07-01 17:19:18
*/
const { bookInfoDB } = require('../db/model/index')
const api = require('./api')

/*
 *@name: 将 subCategories 转换 为所需要的 major，mins对象
 *@param:{type} 
 *@description:
 *@return:
 *@author: panlua
 *@date: 2019-07-01 17:37:25
*/
const type = ['hot', 'new', 'reputation', 'over']
function menuHandle (data) {
  delete data.ok
  delete data.picture
  let menuArr = []
  for (let i in data) {
    data[i].forEach(items => {
      type.forEach(ti => {
        menuArr.push({
          major: items.major,
          minor: '',
          gender: i,
          type: ti
        })
      })
      items.mins.forEach(item => {
        type.forEach(ti => {
          menuArr.push({
            major: items.major,
            minor: item,
            gender: i,
            type: ti
          })
        })
      })
    })
  }
  return menuArr
}

const httpBookTotal = (item) => {
  return new Promise(resolve => {
<<<<<<< HEAD
    AXIOS.get(api.book, {
      params: {
        gender: item.type,
        type: 'hot',
        major: item.major,
        minor: item.minor,
        start: 0,
        limit: 1
      }
    }).then(res => {
      resolve(res.total)
    })
=======
    try {
      AXIOS.get(api.book, {
        params: {
          gender: item.gender,
          type: item.type,
          major: item.major,
          minor: item.minor,
          start: 0,
          limit: 1
        }
      }).then(res => {
        resolve(res.total)
      })
    } catch (err) {
      resolve(0)
    }
>>>>>>> b1ce9388b42cedb929e791e735efc6379a2d75e4
  })
}
/*
 *@name: 查询分类小说数量
 *@param:{type} 
 *@description:
 *@return:
 *@author: panlua
 *@date: 2019-07-01 17:44:28
*/
const getBookTotal = (item) => {
  return new Promise(async(resolve) => {
    const total = await httpBookTotal(item)
<<<<<<< HEAD
    console.log(item, total)
    await LOG.success(`${item.major}/${item.minor}一共${total}本书, 即将采集.........`)
=======
    await LOG.success(`${item.major}/${item.minor}/${item.type}一共${total}本书, 即将采集.........`)
>>>>>>> b1ce9388b42cedb929e791e735efc6379a2d75e4
    for (let i = 0; i < 20; i++) {
      await getBookData(item, i)
    }
    resolve()
  })
}

/*
 *@Description: 获取小说信息
 *@params: 
 *@Author:  lupan
 *@Date: 2019-07-01 19:53:55
*/
const getBookData = (item, start) => {
  return new Promise(async (resolve) => {
    try {
      await AXIOS.get(api.book, {
        params: {
          gender: item.gender,
          type: item.type,
          major: item.major,
          minor: item.minor,
          start: start * 50,
          limit: 50
        }
      }).then(async(res) => {
        const bookData = res.books
        if (!bookData.length) {
          await LOG.success(`${item.major}/${item.minor}/${item.type}全部采集完成`)
          resolve()
          return false
        }
        for (let i = 0; i < bookData.length; i++) {
          delete bookData[i].site
          delete bookData[i].sizetype
          delete bookData[i].superscript
          delete bookData[i].contentType
          delete bookData[i].allowMonthly
          delete bookData[i].banned
          delete bookData[i].latelyFollower
          delete bookData[i].retentionRatio
          delete bookData[i].lastChapter
          await writeBookInfo(bookData[i])
        }
        resolve()
      })
    } catch (err) {
      resolve()
    }
  })
}

/*
 *@Description: 将小说信息写入数据库，并过滤存在的
 *@params: 
 *@Author:  lupan
 *@Date: 2019-07-01 20:02:19
*/

const writeBookInfo = (item) => {
  return new Promise(async (resolve) => {
    const isExist = await bookInfoDB.findById(item._id)
    if (isExist) {
      // 如果书籍已存在，则更新书籍信息
      resolve()
      return false
    }
    const bookOneData = await bookInfoDB.create(item)
    if (bookOneData) {
      await LOG.success(`${item.title}写入成功`)
      await writeLog.addBookLog(item)
    } else {
      await LOG.error(`${item.title}写入失败`)
    }
    resolve()
  })
}

module.exports = async () => {
  let menuArr = []
  try {
    await AXIOS.get(api.subCategories).then(res => {
      menuArr = menuHandle(res)
    })
  } catch (err) {
    LOG.error(`分类获取失败：${err}`)
  }
  for (let i = 0; i < menuArr.length; i++) {
    await getBookTotal(menuArr[i])
  }
  await LOG.success('所有内容写入完成')
}